package com.nmgsr.nettools.net.retrofit;

import com.nmgsr.nettools.net.config.NetManager;
import com.nmgsr.nettools.net.converter.FastJsonConverterFactory;
import com.nmgsr.nettools.util.LogUtil;

import java.util.HashMap;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

public class HttpHelper {

    private OkHttpClient mOkHttpClient;
    private Retrofit retrofit;
    private HashMap<String, Object> serviceMap;

    private static volatile HttpHelper httpHelper;

    public static HttpHelper getInstance() {
        if (httpHelper == null) {
            httpHelper = new HttpHelper();
        }
        return httpHelper;
    }

    private HttpHelper() {
        serviceMap = new HashMap<>();
        mOkHttpClient = OkHttpProvider.getDefaultOkHttpClient();

        LogUtil.e("-----okHttpClient1 = "+mOkHttpClient.hashCode());

        retrofit = new Retrofit.Builder().baseUrl(NetManager.getInstance().getBaseUrl())
                .client(mOkHttpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(FastJsonConverterFactory.create())
                .build();
    }

    public <T> T getService(Class<T> serviceClass) {
        if (serviceMap.containsKey(serviceClass.getName())) {
            return (T) serviceMap.get(serviceClass.getName());
        } else {
            Object object = retrofit.create(serviceClass);
            serviceMap.put(serviceClass.getName(), object);
            return (T) object;
        }
    }

    public OkHttpClient getOkHttpClient()
    {
        return this.mOkHttpClient;
    }
}
